#import "ViewController.h"
#import "Cangjie.h"
#import "unistd.h"

const char * RunCangjie(void) {
    struct RuntimeParam param = {
        .heapParam = {
            .regionSize = 64UL,
            .heapSize = 256 * 1024,
            .exemptionThreshold = 0.8,
            .heapUtilization = 0.6,
            .heapGrowth = 0.15,
            .allocationRate = 10240,
            .allocationWaitTime = 1000 },
            .gcParam = {
                .gcThreshold = 20480,
                .garbageThreshold = 0.5,
                .gcInterval = 150,
                .backupGCInterval = 240,
                .gcThreads = 8},
            .logParam = {.logLevel = RTLOG_ERROR },
            .coParam = { .thStackSize = 64 * 1024, .coStackSize = 32 * 1024, .processorNum = 4 }
    };
    InitCJRuntime(&param);

    if (LoadCJLibraryWithInit("liboccallcj.dylib") != E_OK) {
        printf("Failed to load liboccallcj.dylib.\n");
    }
    void *funcInCj = FindCJSymbol("liboccallcj.dylib", "call_test_pkgnative_windows");
    if(funcInCj == NULL){
        printf("failed to find call_test_pkgnative_windows.\n ");
        return "";
    }

    const char *result = ((const char *(*)(void))funcInCj)();
    NSString *nsString = result ? [NSString stringWithUTF8String:result] : @"(null)";
    NSLog(@"[Cangjie] Native result: %s", result);
    NSLog(@"[Cangjie] NSString result: %@", nsString);
    return result;
}

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupTextView];
    [self displayCangjieResult];
}

- (void)setupTextView {
    self.resultTextView = [[UITextView alloc] initWithFrame:self.view.bounds];
    self.resultTextView.editable = NO;
    self.resultTextView.font = [UIFont systemFontOfSize:16];
    self.resultTextView.backgroundColor = [UIColor whiteColor];
    
    self.resultTextView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.resultTextView];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.resultTextView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
        [self.resultTextView.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor],
        [self.resultTextView.leadingAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.leadingAnchor],
        [self.resultTextView.trailingAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.trailingAnchor]
    ]];
}

- (void)displayCangjieResult {
    const char *cResult = RunCangjie();
    NSString *nsResult = cResult ? [NSString stringWithUTF8String:cResult] : @"faild to load RunCangjie()";
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.resultTextView.text = nsResult;
        [self scrollToBottom];
    });
}

- (void)scrollToBottom {
    NSRange bottom = NSMakeRange(self.resultTextView.text.length - 1, 1);
    [self.resultTextView scrollRangeToVisible:bottom];
}


@end
